<template>
  <div class="prompt-form-container">
    <a-page-header
      :title="isEdit ? '编辑提示词' : '创建提示词'"
      @back="router.push(isEdit ? `/prompts/${promptId}` : '/prompts')"
    />
    
    <a-spin :spinning="loading">
      <a-form
        :model="formState"
        :rules="rules"
        layout="vertical"
        @finish="handleSubmit"
        ref="formRef"
      >
        <a-form-item label="标题" name="title">
          <a-input v-model:value="formState.title" placeholder="输入提示词标题" />
        </a-form-item>
        
        <a-form-item label="描述" name="description">
          <a-textarea 
            v-model:value="formState.description" 
            placeholder="描述这个提示词的用途和特点" 
            :rows="3" 
          />
        </a-form-item>
        
        <a-form-item label="内容" name="content">
          <a-textarea 
            v-model:value="formState.content" 
            placeholder="输入提示词内容" 
            :rows="10" 
            :auto-size="{ minRows: 10, maxRows: 20 }"
          />
        </a-form-item>
        
        <a-form-item label="AI模型" name="ai_model">
          <a-select
            v-model:value="formState.ai_model"
            placeholder="选择适用的AI模型"
            style="width: 100%"
          >
            <a-select-option v-for="model in aiModels" :key="model.id" :value="model.id">
              {{ model.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="formState.tags"
            mode="tags"
            placeholder="添加标签，按Enter创建新标签"
            style="width: 100%"
            :options="tagOptions"
            :filter-option="filterTagOption"
            @search="handleTagSearch"
          />
        </a-form-item>
        
        <a-form-item label="隐私设置" name="is_public">
          <a-radio-group v-model:value="formState.is_public">
            <a-radio :value="true">公开</a-radio>
            <a-radio :value="false">私有</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              {{ isEdit ? '保存修改' : '创建提示词' }}
            </a-button>
            <a-button @click="resetForm">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { usePromptStore } from '../store/prompt';
import { useAuthStore } from '../store/auth';
import { debounce } from 'lodash-es';

export default {
  name: 'PromptForm',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const promptStore = usePromptStore();
    const authStore = useAuthStore();
    
    const formRef = ref(null);
    const promptId = ref(route.params.id);
    const isEdit = computed(() => !!promptId.value);
    const loading = ref(false);
    const aiModels = ref([]);
    const tags = ref([]);
    const tagOptions = ref([]);
    
    const formState = reactive({
      title: '',
      description: '',
      content: '',
      ai_model: undefined,
      tags: [],
      is_public: true
    });
    
    const rules = {
      title: [
        { required: true, message: '请输入提示词标题', trigger: 'blur' },
        { max: 100, message: '标题不能超过100个字符', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入提示词描述', trigger: 'blur' },
        { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入提示词内容', trigger: 'blur' }
      ],
      ai_model: [
        { required: true, message: '请选择AI模型', trigger: 'change' }
      ]
    };
    
    const loadAIModels = async () => {
      try {
        const models = await promptStore.fetchAIModels();
        aiModels.value = models;
      } catch (error) {
        console.error('获取AI模型列表失败:', error);
      }
    };
    
    const loadTags = async () => {
      try {
        const tagList = await promptStore.fetchTags();
        tags.value = tagList;
        updateTagOptions(tagList);
      } catch (error) {
        console.error('获取标签列表失败:', error);
      }
    };
    
    const updateTagOptions = (tagList) => {
      tagOptions.value = tagList.map(tag => ({
        value: tag.id,
        label: tag.name
      }));
    };
    
    const loadPromptDetail = async () => {
      if (!isEdit.value) return;
      
      loading.value = true;
      try {
        const prompt = await promptStore.fetchPromptDetail(promptId.value);
        
        // 检查当前用户是否是提示词的所有者
        if (authStore.user && prompt.user.id !== authStore.user.id) {
          message.error('您没有权限编辑此提示词');
          router.push(`/prompts/${promptId.value}`);
          return;
        }
        
        formState.title = prompt.title;
        formState.description = prompt.description;
        formState.content = prompt.content;
        formState.ai_model = prompt.ai_model.id;
        formState.tags = prompt.tags.map(tag => tag.id);
        formState.is_public = prompt.is_public;
      } catch (error) {
        message.error('获取提示词详情失败');
        console.error(error);
        router.push('/prompts');
      } finally {
        loading.value = false;
      }
    };
    
    const handleSubmit = async () => {
      try {
        loading.value = true;
        
        if (isEdit.value) {
          await promptStore.updateExistingPrompt(promptId.value, formState);
          message.success('提示词更新成功');
          router.push(`/prompts/${promptId.value}`);
        } else {
          const newPrompt = await promptStore.createNewPrompt(formState);
          message.success('提示词创建成功');
          router.push(`/prompts/${newPrompt.id}`);
        }
      } catch (error) {
        const errorMsg = isEdit.value ? '更新提示词失败' : '创建提示词失败';
        message.error(errorMsg);
        console.error(error);
      } finally {
        loading.value = false;
      }
    };
    
    const resetForm = () => {
      formRef.value.resetFields();
    };
    
    const filterTagOption = (input, option) => {
      return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };
    
    const handleTagSearch = debounce(async (value) => {
      if (!value) return;
      
      try {
        const searchedTags = await promptStore.fetchTags(value);
        updateTagOptions(searchedTags);
      } catch (error) {
        console.error('搜索标签失败:', error);
      }
    }, 300);
    
    onMounted(() => {
      loadAIModels();
      loadTags();
      loadPromptDetail();
    });
    
    return {
      router,
      formRef,
      promptId,
      isEdit,
      loading,
      formState,
      rules,
      aiModels,
      tagOptions,
      handleSubmit,
      resetForm,
      filterTagOption,
      handleTagSearch
    };
  }
};
</script>

<style scoped>
.prompt-form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem 1rem;
}
</style>